package com.scholarship.system.controller;

import com.scholarship.system.common.dto.LoginRequest;
import com.scholarship.system.common.dto.LoginResponse;
import com.scholarship.system.common.dto.Result;
import com.scholarship.system.entity.User;
import com.scholarship.system.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * 认证控制器
 */
@RestController
@RequestMapping("/auth")
public class AuthController {

    private static final Logger log = LoggerFactory.getLogger(AuthController.class);

    @Autowired
    private UserService userService;

    /**
     * 登录
     */
    @PostMapping("/login")
    public Result<LoginResponse> login(@Valid @RequestBody LoginRequest loginRequest) {
        log.info("用户尝试登录: username={}, role={}", loginRequest.getUsername(), loginRequest.getRole());
        Result<LoginResponse> result = userService.login(loginRequest);
        if (result.getCode() == 200) {
            log.info("用户登录成功: {}", loginRequest.getUsername());
        } else {
            log.warn("用户登录失败: {}, 原因: {}", loginRequest.getUsername(), result.getMessage());
        }
        return result;
    }

    /**
     * 获取用户信息
     */
    @GetMapping("/info")
    public Result<LoginResponse.UserInfo> getUserInfo() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        log.info("获取用户信息: {}, 认证详情: {}", authentication.getName(), authentication);
        return userService.getUserInfo(authentication.getName());
    }

    /**
     * 注册导师账号
     */
    @PostMapping("/register")
    public Result<User> register(@Valid @RequestBody User user) {
        log.info("用户注册: username={}, role={}", user.getUsername(), user.getRole());
        try {
            // 检查用户名是否已存在
            User existUser = userService.getByUsername(user.getUsername());
            if (existUser != null) {
                log.warn("注册失败: 用户名已存在, username={}", user.getUsername());
                return Result.error("用户名已存在");
            }

            // 确保角色为TEACHER
            user.setRole("TEACHER");

            // 保存用户
            userService.addUser(user);
            log.info("用户注册成功: {}", user.getUsername());
            return Result.success(user);
        } catch (Exception e) {
            log.error("用户注册失败", e);
            return Result.error("注册失败: " + e.getMessage());
        }
    }

    /**
     * 获取认证状态（用于诊断）
     */
    @GetMapping("/status")
    public Result<Map<String, Object>> getAuthStatus(HttpServletRequest request) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        Map<String, Object> status = new HashMap<>();
        status.put("authenticated", authentication != null && authentication.isAuthenticated());
        status.put("principal", authentication != null ? authentication.getPrincipal().toString() : "null");
        status.put("authorities", authentication != null ? authentication.getAuthorities() : "null");
        status.put("authorizationHeader", request.getHeader("Authorization"));

        log.info("认证状态检查: {}", status);

        return Result.success(status);
    }

    /**
     * 退出登录
     */
    @PostMapping("/logout")
    public Result<Void> logout(HttpServletRequest request) {
        // 清除安全上下文
        SecurityContextHolder.clearContext();
        log.info("用户已退出登录");
        return Result.success();
    }
}